import { Form, Input, Button, Avatar } from "antd";
import { UserOutlined, LockOutlined } from "@ant-design/icons";
import { login, LoginParams } from "@/store/app/appAPI";
import { setUserInfo } from "@/store/app/appSlice";
import local from "@/utils/local";
import { useNavigate } from "react-router-dom";
import type { NavigateFunction } from 'react-router-dom'
import { useState } from "react";
import { useAppDispatch } from "@/store/hooks";

export default function Login() {
  const dispatch = useAppDispatch();
  const navigate:NavigateFunction = useNavigate();
  const [isLoading, setIsLoading] = useState<boolean>(false)
  const onFinish = (params: LoginParams):void => {
    setIsLoading(true)
    login(params).then(({data}):void => {
      const userInfo = {
        ...data,
        userName: params.username
      }
      dispatch(setUserInfo(userInfo))
      local.set('userInfo', userInfo)
      navigate('/')
    }).finally(():void => {setIsLoading(false)});
  };
  return (
    <div className="max-w-[350px] mt-[64px] mx-auto">
      <div className="m-[0_auto_12px] flex justify-center flex-col items-center">
        <Avatar shape="square" size={50} icon={<img src='/logo.jpg' />} />
        <h1 className="text-[20px] font-semibold">Diamond Galaxy</h1>
      </div>
      <Form onFinish={onFinish}>
        <Form.Item
          name="username"
          rules={[{ required: true, message: "请输入账号" }]}
        >
          <Input
            prefix={<UserOutlined />}
            className="h-[50px]"
            placeholder="账号"
          />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[{ required: true, message: "请输入密码" }]}
        >
          <Input.Password
            prefix={<LockOutlined />}
            className="h-[50px]"
            placeholder="密码"
          />
        </Form.Item>
        <Form.Item>
          <Button
            htmlType="submit"
            className="w-full"
            type="primary"
            size="large"
            loading={isLoading}
          >
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
}
